package com.naizhuai.util;

import android.accounts.NetworkErrorException;

import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;

import retrofit2.adapter.rxjava.HttpException;
import rx.Observable;
import rx.functions.Func1;

/**
 * Created by code_han on 2018/4/26.
 */

public class RetryWithDelay implements Func1<Observable<? extends Throwable>, Observable<?>> {
    private final int maxRetries;
    private final int retryDelayMillis;
    private int retryCount;

    public RetryWithDelay(int maxRetries, int retryDelayMillis) {
        this.maxRetries = maxRetries;
        this.retryDelayMillis = retryDelayMillis;
    }

    @Override
    public Observable<?> call(Observable<? extends Throwable> attempts) {
        return attempts.flatMap(new Func1<Throwable, Observable<?>>() {
            @Override
            public Observable<?> call(Throwable throwable) {
                NaizhuAILog.e("throwable's details " + throwable.getMessage());
                if (retryException(throwable) && ++retryCount <= maxRetries) { // When this Observable calls onNext, the original Observable will be retried (i.e. re-subscribed).
                    NaizhuAILog.e("get error, it will try after " + retryDelayMillis + " millisecond, retry count " + retryCount);
                    return Observable.timer(retryDelayMillis, TimeUnit.MILLISECONDS);
                } // Max retries hit. Just pass the error along.
                return Observable.error(throwable);
            }
        });
    }

    private boolean retryException(Throwable throwable) {
        return throwable instanceof NetworkErrorException || throwable instanceof SocketTimeoutException;
    }

}
